package com.iamalive;

import java.util.ArrayList;

import org.apache.http.entity.StringEntity;

import com.iamalive.LocalCache.InfoDetails;
import com.iamalive.LocalCache.RecipientDetails;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends Activity {
	private EditText mEditTextUsername;
	private EditText mEditTextPassword;
	private Button mButtonLogin;
	private Button mButtonSignup;
	private Context mContext;
	private String mEmailId, mPassword;
	
	private String mPreferencesFile;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mEditTextUsername = (EditText) findViewById(R.id.editTextUsername);
		mEditTextPassword = (EditText) findViewById(R.id.editTextPassword);
		mButtonLogin = (Button) findViewById(R.id.buttonLogin);
		mButtonSignup = (Button) findViewById(R.id.buttonSignup);
		mContext = this;
		mPreferencesFile = getResources().getString(R.string.preferences_file_name);
		
		populateLoginCredentials();
		
		mButtonLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onLoginButtonClicked(v);
            }
        }); 
		
		mButtonSignup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onSignupButtonClicked();
            }
        }); 
	}
	
	private void populateLoginCredentials() {
		SharedPreferences settings = getSharedPreferences(mPreferencesFile, 0);
		if(settings != null) {
			String emailId = settings.getString(getResources().getString(R.string.login_id), "");
			String password = settings.getString(getResources().getString(R.string.login_password), "");
			mEditTextUsername.setText(emailId);
			mEditTextPassword.setText(password);
		}
	}
	
	private void onLoginButtonClicked(View v) {
		mEmailId = mEditTextUsername.getText().toString();
		mPassword = mEditTextPassword.getText().toString();

		validateUserNameAndPassword(v, mEmailId, mPassword);
	}
	
	 private void persistLoginCredentials() {		 
		SharedPreferences settings = getSharedPreferences(mPreferencesFile, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(getResources().getString(R.string.login_id), mEmailId);
		editor.putString(getResources().getString(R.string.login_password), mPassword);
		editor.commit();
	 }

	private void onSignupButtonClicked() {
		Intent i = new Intent(this, SignupActivity.class);
	    startActivity(i);		
	}
	
	private boolean validateUserNameAndPassword(View v, String username, String password) {
		boolean bRetVal = true;
		
		String loginXml = XmlReaderWriter.assembleLoginRequest(mEmailId, mPassword);
		StringEntity s = Utils.getStringEntity(loginXml);
		//s.setContentType("text/xml");

		ImaRestClient restClient = new ImaRestClient();
		restClient.post(mContext, "login", s, new String("text/xml"), new AsyncHttpResponseHandler() {
			private ProgressDialog pd;
			
			@Override
			public void onStart() {
				pd = new ProgressDialog(mContext);
				pd.setTitle("Processing...");
				pd.setMessage("Please wait while I validate credentials");
				pd.setCancelable(false);
				pd.setIndeterminate(true);
				pd.show();				
            }
			
			@Override
			public void onSuccess(String response) {
				pd.dismiss();
				ArrayList<String> messageList = new ArrayList<String>();
				
				boolean bSaveCredentials = ((CheckBox)findViewById(R.id.checkBoxSaveUSernamePassword)).isChecked();
				
				if(true == XmlReaderWriter.parseLoginResponse(response, messageList)) {
					if(LocalCache.getSingleInstance().mUserValidated == true) {
						Utils.showToast(mContext, "Login successful");
						if(true == bSaveCredentials) {
							persistLoginCredentials();
						}
						Intent i = new Intent(mContext, OptionsActivity.class);
						startActivity(i);
					} else {
						Utils.showToast(mContext, "Credentials are incorrect!!!");
					}
				} else {
					Utils.showToast(mContext, "Oops!!! Something went wrong during communication!!!");
				}
            }

            @Override
            public void onFailure(Throwable throwable) {
            	pd.dismiss();
            	Utils.showToast(mContext, "Exeption received");
            }
		});
		
		return bRetVal;
	}
		

	
	
	
//	private boolean validateUserNameAndPassword(View v, String username, String password) {
//		boolean bRetVal = true;
//		
//		 //v.setEnabled(false);
//
//		 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
//			 private ProgressDialog pd;
//
//			 @Override
//			 protected void onPreExecute() {
//				 pd = new ProgressDialog(mContext);
//				 pd.setTitle("Processing...");
//				 pd.setMessage("Please wait while I validate credentials");
//				 pd.setCancelable(false);
//				 pd.setIndeterminate(true);
//				 pd.show();
//			 }
//
//			 private StatusLine doPost(String c) throws ClientProtocolException, IOException {
//				 String url = new String("http://212.71.251.23:9001/axis2/services/ima/login");
//				 DefaultHttpClient httpclient = new DefaultHttpClient();
//				 HttpPost request = new HttpPost(url);
//				 StringEntity s = new StringEntity(c.toString());
//			         
//				 s.setContentEncoding("UTF-8");
//				 s.setContentType("text/xml");
//
//				 request.setEntity(s);
//				 // request.addHeader("accept", "text/xml");
//
//				 HttpResponse resp = httpclient.execute(request);
//
//				 StatusLine line = resp.getStatusLine();
//
//				 String message = resp.getStatusLine().getReasonPhrase();
//				 HttpEntity entity = resp.getEntity();
//
//				 if(entity != null) {
//					 InputStream instream = entity.getContent();
//					 String response = Utils.convertStreamToString(instream);
//					 // Closing the input stream will trigger connection release
//					 instream.close();
//				 }
//			        
//				 return line;			 
//			 }
//
//
//			 @Override
//			 protected Void doInBackground(Void... arg0) {
//				 try {
//					 //Do something...
//					 Thread.sleep(5000);
//					//TODO: make a web service call here
//					 /*AsyncHttpClient client = new AsyncHttpClient();
//					 client.get("http://www.google.com", new AsyncHttpResponseHandler() {
//					     @Override
//					     public void onSuccess(String response) {
//					         System.out.println(response);
//					     }
//					 }); */
//					String loginXml = XmlReaderWriter.assembleLoginRequest(mEmailId, mPassword);
//					
//					try {
//						doPost(loginXml);
//					} catch (ClientProtocolException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					
//					/*ImaRestClient.post(mContext, "login", Utils.getStringEntity(loginXml), getResources().getString(R.string.content_type_xml), new AsyncHttpResponseHandler() {
//					     @Override
//					     public void onSuccess(String xmlResponse) {
//					    	 //TODO parse the xml response and set the value of variable LocalCache.mUserValidated = true;
//					    	 
//					         System.out.println(xmlResponse);
//					     }
//					 }); */
//					Utils.showToast(mContext, new String("Done with calling web-service"));
//
//				 } catch (InterruptedException e) {
//					 // TODO Auto-generated catch block
//					 e.printStackTrace();
//				 }
//				 return null;
//			 }
//			 
//			 
//
//			 @Override
//			 protected void onPostExecute(Void result) {
//				 
//				 pd.dismiss();
//				 //findViewById(R.id.the_button).setEnabled(true);
//				 //Utils.showToast(mContext, new String("Done with calling web-service"));
//			 }
//        };
//
//        task.execute((Void[])null);
//        return bRetVal;
//	}

	private void fetchUserSpecificData(String emailId, String tokenId) {
		
	}
	
	private void populateLocalCacheWithFakeData() {
		LocalCache localCache = LocalCache.getSingleInstance();
		RecipientDetails recipient = localCache.new RecipientDetails();
		recipient.id = 123;
		recipient.name = "KN";
		recipient.email = "kn@gmail.com";
		localCache.mRecipientDetailsMap.put(recipient.name, recipient);
		
		recipient = localCache.new RecipientDetails();
		recipient.id = 456;
		recipient.name = "KN1";
		recipient.email = "kn1@gmail.com";
		localCache.mRecipientDetailsMap.put(recipient.name, recipient);
		
		recipient = localCache.new RecipientDetails();
		recipient.id = 789;
		recipient.name = "KN2";
		recipient.email = "kn2@gmail.com";
		localCache.mRecipientDetailsMap.put(recipient.name, recipient);
		
		InfoDetails infoDetails = localCache.new InfoDetails();
		infoDetails.id = 2;
		infoDetails.infoBody = "FD at vasant vihar; no: 123 Rs. 10000/ maturity in July take it in 2000. FD at vasant vihar; no: 123 Rs. 10000/ maturity in July take it in 2000. FD at vasant vihar; no: 123 Rs. 10000/ maturity in July take it in 2000";
		infoDetails.listOfRecipients.add(new String("KN"));
		infoDetails.listOfRecipients.add(new String("KN2"));
		localCache.mInfoList.add(infoDetails);
		
		infoDetails = localCache.new InfoDetails();
		infoDetails.id = 3;
		infoDetails.infoBody = "lent money to Suresh";
		infoDetails.listOfRecipients.add(new String("KN1"));
		infoDetails.listOfRecipients.add(new String("KN2"));
		localCache.mInfoList.add(infoDetails);	
		
		localCache.mUserDetails.name = new String("Kamal Nandan");
		localCache.mUserDetails.password = new String("password");
		localCache.mUserDetails.emailId = new String("kn@gmail.com");
		localCache.mUserDetails.imId = new String("kamalnroy@yahoo.com");
		
	}
}
